// CountManager.java: Servant Locator for count objects
package Server2;

import org.omg.PortableServer.*;
import org.omg.PortableServer.POAPackage.ObjectNotActive;
import org.omg.PortableServer.POAPackage.WrongPolicy;

import java.util.Random;
import java.io.*;
import java.util.ArrayList;

public class CountManagerActivator extends ServantActivatorPOA
{
	private final int servantLimit;
	private int activeServants;
	private ArrayList<byte[]> idArray;
	
	public CountManagerActivator() {
		servantLimit = 1000;
		activeServants = 0;
		idArray = new ArrayList<byte[]>();
	}

	public CountManagerActivator(int limit) {
		servantLimit = limit;
		activeServants = 0;
		idArray = new ArrayList<byte[]>();
	}
	
    public Servant incarnate(byte[] objectID, POA poa)
    {
//		System.out.println(".....incarnate called for object ID "+new String(objectID));
//		System.out.println(".....creating new servant");
//		System.out.println(".....activeServants = " + activeServants);
		
		if (activeServants < servantLimit) {
			try
		    {
				CountPOAServant servant = new CountPOAServant();

				FileInputStream f_In = new FileInputStream( new String(objectID)+".state");
				BufferedReader b_In = new BufferedReader(new InputStreamReader(f_In));
				int sum = Integer.parseInt(b_In.readLine());
				b_In.close();
				f_In.close();
				
				servant.sum(sum);
				
				idArray.add(objectID);
				activeServants++;

				return servant;
		    }
			catch(Exception E)
		    {
				System.out.println(".....exception encountered during state restore.");
				return null;
		    }
		} else {
			  Random randomGen = new Random();
			  
			  int random = randomGen.nextInt(activeServants);
			  byte[] deactivateID = idArray.remove(random);
			  
			try {
				poa.deactivate_object(deactivateID);
			} catch (ObjectNotActive e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (WrongPolicy e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			  
//			  System.out.println(".....objectID to etherealize: " + new String(deactivateID));
//			  etherealize(deactivateID, poa, servantToDeactivate, false, false);
			  activeServants--;
			  
			  return incarnate(objectID, poa);
		}
    }

    public void etherealize(byte[] objectID, POA poa, Servant servant, boolean cleanup_in_progress, boolean remaining_activations)
    {
//    	System.out.println(".....etherealize called for object ID "+new String(objectID));
	
    	try
	    {

			FileOutputStream f_Out = new FileOutputStream( new String(objectID)+".state");
			PrintWriter b_Out = new PrintWriter(new OutputStreamWriter(f_Out));
			int sum = ((CountPOAServant)(servant)).sum();
			b_Out.println(""+sum);
			b_Out.close();
			f_Out.close();
			
    		poa.deactivate_object(objectID);

	    }
    	catch(Exception E)
	    {
    		System.out.println(".....EXCEPTION encountered during state save.");
	    }
	
    }
}
